package service

import (
	"fmt"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"github.com/xuri/excelize/v2"
	"os"
	"path/filepath"
)

func UploadFile(sid string, content []byte, fileType string) (link string, err error) {
	root := viper.GetString("fslocation")
	dir1 := sid[:2]
	dir2 := sid[2:4]
	path := filepath.Join(root, dir1, dir2)
	err = os.MkdirAll(path, os.ModePerm)
	if err != nil {
		return
	}
	link = filepath.Join(dir1, dir2, sid)
	//if fileType != "text/plain" {
	//	link += "." + fileType
	//}
	//if fileType == "image/png" {
	//	link += ".png"
	//} else if fileType == "image/jpeg" {
	//	link += ".jpg"
	//} else if fileType == "text/xml" {
	//	link += ".xml"
	//} else if fileType == "text/plain" {
	//	link += ".txt"
	//} else if fileType == "text/html" {
	//	link += ".html"
	//}
	log.Info(fmt.Sprintf("upload file type is %s", fileType))

	// 写到磁盘上
	err = os.WriteFile(filepath.Join(root, link), content, 0644)
	if err != nil {
		return
	}
	return
}

func DownloadFile(link string) (content []byte, err error) {
	root := viper.GetString("fslocation")
	path := filepath.Join(root, link)
	return os.ReadFile(path)
}

func DeleteFile(link string) (err error) {
	root := viper.GetString("fslocation")
	path := filepath.Join(root, link)
	return os.Remove(path)
	return nil
}

func OpenExcel(link string) (*excelize.File, error) {
	root := viper.GetString("fslocation")
	path := filepath.Join(root, link)
	f, err := excelize.OpenFile(path, excelize.Options{
		ShortDatePattern: "yyyy/mm/dd",
	})
	if err != nil {
		log.Error(err)
		return nil, err
	}
	return f, nil
}
